package org.elephas.webapp.frontend.component;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.elephas.webapp.application.ElephasSession;
import org.elephas.webapp.frontend.component.common.form.ShinyForm;

public class LoginFormPanel extends Panel {
	private static final long serialVersionUID = 1L;

	private String email;
	private String password;

	public LoginFormPanel(String id) {
		super(id);

		ShinyForm form = new ShinyForm("form");
		add(form);
		form.add(new RequiredTextField("email",
				new PropertyModel(this, "email")));
		form.add(new PasswordTextField("password", new PropertyModel(this,
				"password")));

		form.add(new AjaxButton("submit", form) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				if (!ElephasSession.get().signIn(email, password)) {
					error(getString("login.error"));
				} else {
					onLoginSucceeded(target);
				}
			}
			
			@Override
			protected void onError(AjaxRequestTarget target, Form form) {
				target.addComponent(form);
			}
		});
	}

	protected void onLoginSucceeded(AjaxRequestTarget target) {
		setResponsePage(getPage());
	}
	
	protected void onLoginCanceled(AjaxRequestTarget target) {

	}

}
